package com.ziki.bswicket.component;

import java.util.List;
import java.util.Map;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.util.string.AppendingStringBuffer;

import com.ziki.framework.wicket.markup.html.form.FwChoiceData;
import com.ziki.framework.wicket.markup.html.form.FwDropDownChoice;

public class BsDropDownGroup<T> extends FwDropDownChoice<T> {
    private static final long serialVersionUID = 1L;
    private FwChoiceData<T> choiceData;

    public BsDropDownGroup(String id) {
        super(id);
    }

    public BsDropDownGroup(String id, FwChoiceData<T> choices) {
        super(id, choices.getList(), choices.getChoiceRender());
        this.choiceData = choices;
    }

    @Override
    public void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {
        List<? extends T> choices = getChoices();
        final AppendingStringBuffer buffer = new AppendingStringBuffer((choices.size() * 50) + 16);
        final String selectedValue = getValue();

        // Append default option
        buffer.append(getDefaultChoice(selectedValue));

        Map<String, List<T>> groupList = choiceData.getGroupList();
        int i = 0;
        for (String group : groupList.keySet()) {
            List<? extends T> lstChoices = groupList.get(group);
            buffer.append("<optgroup label=\"" + group + "\">");
            for (int index = 0; index < lstChoices.size(); index++) {
                final T choice = lstChoices.get(index);
                appendOptionHtml(buffer, choice, i, selectedValue);
                i++;
            }
            buffer.append("</optgroup>");
        }
        buffer.append("\n");
        replaceComponentTagBody(markupStream, openTag, buffer);
    }
}
